package com.dataStructure.leetcode.链表;

public class 反转一个链表 {

    /**
     * https://leetcode-cn.com/problems/reverse-linked-list/
     * 使用递归和非递归的两种方式实现
     */

    //递归
    public static   ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) return head;

        ListNode newNode = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newNode;
    }

    //迭代
    public static ListNode reverseList1(ListNode head){
        ListNode newHead = null;
        ListNode temp = null;

        while (head != null) {
            temp = head.next;
            head.next = newHead;
            newHead = head;
            head = temp;
        }
        return newHead;
    }

    public static void main(String[] args) {
        // 初始化单链表
        ListNode node5 = new ListNode(5,null);
        ListNode node4 = new ListNode(4,node5);
        ListNode node3 = new ListNode(3,node4);
        ListNode node2 = new ListNode(2,node3);
        ListNode node1 = new ListNode(1,node2);

        // 调用反转方法
        ListNode recursiveList = reverseList(node1);
        System.out.println(recursiveList);
    }

}
